package cfl.activemq.com.topics;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import cfl.activemq.com.config.ActiveMQConfig;

/**
 * 生产者
 * @author chenfenli
 *
 */
public class TopicsProducer {

	public static void main(String[] args) {
		
		ConnectionFactory connectionFactory;
		Connection connection = null;
		try {
			// 1.创建链接工厂
			connectionFactory = new ActiveMQConnectionFactory(ActiveMQConfig.UASENAME, ActiveMQConfig.PASSWORD, ActiveMQConfig.BROKEURL);
			
			// 2.创建链接对象
			connection = connectionFactory.createConnection();
			
			// 3.启动链接
			connection.start();
			
			// 4.创建session会话 true:并且开启事务
			Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			
			// 5.创建消息订阅
			Destination destination = session.createTopic("Topics测试");
			
			// 6.创建生产者
			MessageProducer messageProducer = session.createProducer(destination);
			
			// 7.发布订阅
			sendMessage(session, messageProducer);
			
			// 8.提交
			session.commit();
			
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			// 关闭链接
			if(connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	/*
	 * 发送订阅消息
	 */
	public static void sendMessage(Session session, MessageProducer messageProducer) {
		Message message;
		try {
			message = session.createTextMessage("activemq_topics 发送的消息 ");
			messageProducer.send(message);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}
